package utils

import (
	"github.com/labstack/echo"
	"strconv"
)

const defaultPageLimit = 10
const maxPageLimit = 50

// Result represents HTTP response body.
type Result struct {
	Err  interface{} `json:"err"`  // error message
	Data interface{} `json:"data"` // data object
}

// NewResult creates a result with Code=0, Msg="", Data=nil.
func NewResult(params ...interface{}) *Result {
	paramLen := len(params)
	if paramLen == 0 {
		return &Result{
			Err:  nil,
			Data: nil,
		}
	} else if paramLen == 1 {
		return &Result{
			Err:  nil,
			Data: params[0],
		}
	} else {
		return &Result{
			Err:  params[0],
			Data: params[1],
		}
	}
}

// PaginationResult represents reponse body with pagination
type PaginationResult struct {
	Result
	Total  int `json:"total"`
	Limit  int `json:"limit"`
	Offset int `json:"offset"`
}

// NewPaginationResult create a paginationResult with default value
func NewPaginationResult() *PaginationResult {
	return &PaginationResult{
		Result: Result{
			Err:  nil,
			Data: nil,
		},
		Total:  0,
		Offset: 0,
		Limit:  defaultPageLimit,
	}
}

func Paginate(ctx echo.Context) (*PaginationResult, error) {
	page, err := strconv.Atoi(ctx.QueryParam("page"))
	if err != nil {
		page = 1
	}
	if page <= 0 {
		page = 1
	}
	limit, err := strconv.Atoi(ctx.QueryParam("limit"))
	if err != nil {
		limit = defaultPageLimit
	}
	if maxPageLimit < limit || limit <= 0 {
		limit = defaultPageLimit
	}
	result := NewPaginationResult()
	result.Limit = limit
	result.Offset = (page - 1) * limit
	return result, nil
}
